<template>
    <view class="relationGoods">
        <uni-nav-bar fixed left-icon="left" title="关联商品" @clickLeft="backHandle" class="unibarS">
            <block slot="right">
                <text class="sub-btn" @click="addGoods">添加商品</text>
            </block>
        </uni-nav-bar>
        <view class="customer-info">
            <view>
                <view class="num">{{ selectList.length }}条</view>
                <view class="name">商品数量</view>
            </view>
            <view>
                <view class="num">{{ totalNum }}个</view>
                <view class="name">商品总数量</view>
            </view>
            <view>
                <view class="num">¥{{ totalPrice }}</view>
                <view class="name">商品总金额</view>
            </view>
        </view>
        <view class="list">
            <template v-if="list.length">
                <view class="item" v-for="(item, index) in list" :key="index">
                    <view class="title">{{ item.commodityName }}</view>
                    <view class="sn">产品规格：{{ bus_product_specification_unit[item.specificationId] }}</view>
                    <view class="price">
                        <view>
                            <u--input
                                style="width: 70px;"
                                placeholder="单价"
                                border="surround"
                                v-model="item.unitPrice"
                                type="number">
                            </u--input>
                        </view>
                        <!-- <view class="money">¥{{ item.caseUnitPrice }}</view> -->
                        <view style="display: flex;">
                            <u-icon name="minus-circle" size="24"  @click.native.stop="circleHandle(index)"></u-icon>
                            <text style="width: 30px;text-align: center;" class="input">{{ item.quantity }}</text>
                            <u-icon name="plus-circle-fill" color="#677585" size="24" @click.native.stop="plusHandle(index)"></u-icon>
                        </view>
                    </view>
                    <view class="total">总价(元)：{{ item.subtotal }}</view>
                    <view class="icon-box" @click="selectHandle(item)">
                        <image :src="getIcon(item)" style="width: 28px; height: 22px;"></image>
                    </view>
                </view>
            </template>
            <template v-else>
                <u-empty
                    mode="data"
                    :icon="empty">
                </u-empty>
            </template>
        </view>
        <!-- 底部 -->
        <view class="bottom-box">
            <view class="next" @click="subHandle()">保存</view>
        </view>
    </view>
</template>

<script>
import { convertToDict, formatNumber } from '@/common/utils'
export default {
    data() {
        return {
            totalQuantity: 0,
            list: [],
            empty: '/static/img/other/empty.png',
            defaultIcon: '/static/img/other/d-icon.png',
            activeIcon: '/static/img/other/a-icon.png',
            selectList: [],
            totalNum: 0,
            totalPrice: 0
        }
    },
    watch: {
        selectList: {
            handler(newVal, oldVal) {
                this.totalNum = newVal.reduce((acc, item) => formatNumber(acc + Number(item.quantity)), 0);
                this.totalPrice = newVal.reduce((acc, item) => formatNumber(acc + Number(item.unitPrice) * Number(item.quantity)), 0);
            },
            deep: true,
            immediate: true
        },
        list: {
            handler(newVal, oldVal) {
                newVal.forEach((item, index) => {
                    let num = formatNumber(Number(item.unitPrice) * Number(item.quantity))
                    this.$set(this.list[index], 'subtotal', num)
                    this.$forceUpdate()
                })
                this.updateSelectList(newVal);
            },
            deep: true,
            immediate: true
        }
    },
    onLoad: function(option) {
        // 提醒方式
        this.bus_product_specification = JSON.parse(uni.getStorageSync('bus_product_specification_unit'))
        this.bus_product_specification_unit = convertToDict(this.bus_product_specification)

        const eventChannel = this.getOpenerEventChannel();
        let that = this
        // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
        eventChannel.on('emitDataHandle', function(data) {
            if(!data.data.length) return
            that.list = JSON.parse(JSON.stringify(data.data))
            that.selectList = JSON.parse(JSON.stringify(data.data))
        })
    },
    methods: {
        addGoods() {
            let that = this
            uni.navigateTo({
                url: '/pages/goods/selectGoods',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    someEvent: function (data) {
                        let list = JSON.parse(JSON.stringify(data.data))
                        that.list = list
                        that.$forceUpdate()
                    },
                },
                success: function (res) {
                    console.log('success:' + JSON.stringify(res))
                    let arr = JSON.parse(JSON.stringify(that.list))
                    res.eventChannel.emit('emitDataHandle', { data: arr })
                }
            });
        },
        // 
        subHandle() {
            if(!this.selectList.length) {
                uni.showToast({
                    title: '请选择商品',
                    icon: 'none'
                })
                return
            }
            const eventChannel = this.getOpenerEventChannel();
            let list = JSON.parse(JSON.stringify(this.selectList))
            let obj = {
                list: list,
                totalPrice: this.totalPrice,
            }
            eventChannel.emit('someEvent', {data: obj});
            uni.navigateBack()
        },
        seeMoney() {
            this.$refs.popup.open()
        },
        closePopup() {
            this.$refs.popup.close()
        },
        circleHandle(index){
            if (this.list[index].quantity <= 1) return
            this.list[index].quantity --
            this.$forceUpdate()
        },
        plusHandle(index){
            let num = Number(Number(this.list[index].quantity) + 1)
            this.$set(this.list[index], 'quantity', num)
            this.$forceUpdate()
        },
        updateSelectList(newList) {
            newList.forEach(item => {
                const index = this.selectList.findIndex(selectItem => selectItem.id === item.id);
                if (index !== -1) {
                    this.$set(this.selectList, index, { ...this.selectList[index], ...item });
                }
            });
        },
        selectHandle(item) {
            const index = this.selectList.findIndex(selectItem => selectItem.id === item.id);
            if (index !== -1) {
                // 如果找到了，说明包含该项，删除它
                this.selectList.splice(index, 1);
            } else {
                // 如果没有找到，说明不包含该项，添加它
                this.selectList.push(item);
            }
            console.log(this.selectList)
        },
        getIcon(item) {
            return this.selectList.some(selectItem => selectItem.id === item.id) ? this.activeIcon : this.defaultIcon;
        },
        backHandle() {
            uni.navigateBack()
        }
    }
}
</script>

<style lang="scss" scoped>
/deep/.uni-navbar__header-btns-right {
    width: 70px !important;
}

.relationGoods {
    padding-bottom: 40px;
}

.list {
    padding-bottom: 40rpx;
}

.item {
    padding: 32rpx;
    border-radius: 24rpx;
    background: rgba(255, 255, 255, 1);
    margin-bottom: 32rpx;
    display: flex;
    flex-direction: column;
    position: relative;

    .title {
        font-size: 36rpx;
        font-weight: 500;
        color: rgba(12, 16, 25, 1);
        margin-bottom: 20rpx;
        // 超出隐藏
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .sn {
        font-size: 28rpx;
        font-weight: 400;
        color: rgba(103, 117, 133, 1);
        margin-bottom: 28rpx;
    }

    .price {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 46rpx;

        .money {
            font-size: 40rpx;
            color: rgba(255, 0, 28, 1);
        }
    }

    .total {
        font-size: 32rpx;
        font-weight: 400;
        color: rgba(12, 16, 25, 1);
        text-align: right;
    }

    .icon-box {
        position: absolute;
        right: 0;
        top: 0;
    }
}

.customer-info {
    border-radius: 24px;
    background: rgba(77, 172, 177, 1);
    padding: 36rpx 40rpx;
    margin: 32rpx;
    color: rgba(255, 255, 255, 1);
    display: flex;
    justify-content: space-around;

    >view {
        text-align: center;

        .num {
            font-size: 44rpx;
            font-weight: 500;
            color: rgba(255, 255, 255, 1);
            margin-bottom: 16rpx;
        }

        .name {
            font-size: 28rpx;
            font-weight: 400;
            color: rgba(255, 255, 255, 1);
        }
    }
}

.bottom-box {
    height: 60px;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 24rpx 32rpx;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    .next {
        width: 100%;
        text-align: center;
        padding: 20rpx 60rpx;
        border-radius: 60px;
        background: #4DACB1;
        font-size: 30rpx;
        font-weight: 500;
        color: rgba(255, 255, 255, 1);
    }
}

.minus {
    width: 22px;
    height: 22px;
    border-width: 1px;
    border-color: #E6E6E6;
    border-style: solid;
    border-top-left-radius: 100px;
    border-top-right-radius: 100px;
    border-bottom-left-radius: 100px;
    border-bottom-right-radius: 100px;
    @include flex;
    justify-content: center;
    align-items: center;
}

.input {
    padding: 0 10px;
}

.plus {
    width: 22px;
    height: 22px;
    background-color: #FF0000;
    border-radius: 50%;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    justify-content: center;
    align-items: center;
}
</style>